public class HashBucket {

    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    private int usedSize = 0;
    private Node[] array;
    private final static double LOAD_FACTOR = 0.75;//默认负载因子
    private static final int DEFAULT_SIZE = 8;//默认桶的大小（链表长度）

    /**
     * 存入元素
     */
    public int put(int key, int val) {
       int index = key % array.length;//确定映射关系
       Node node = new Node(key,val);
       Node cur = array[index];
       while (cur != null) {
           //去重
           if(cur.key == key) {
               cur.val = val;
               return -1;//元素重复，只需修改
           }
           cur = cur.next;
       }
       //采用尾插
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if(loadFactor() > LOAD_FACTOR) {
           reSize();
        }
        return -1;
    }


    /**
     * 扩容以及重新哈希
     */
    private void reSize() {
        Node[] newArray = new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null) {
                Node nextCur = cur.next;
                int index = cur.key % newArray.length;

                cur.next = newArray[index];
                newArray[index] = cur;
                cur = nextCur;
            }
        }

        array = newArray;
    }


    /**
     * 计算当前的负载因子大小
     * @return
     */
    private double loadFactor() {
        return usedSize * 1.0 / array.length;
    }


    public HashBucket() {
        // write code here
        array = new Node[10];
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }



}
